<template>
	<div class="container">
		<el-dialog
			title="物品借出"
			:visible.sync="showDialog_copy"
			class="main_dialog_copy dialog800"
			@closed="closed"
		>
			<el-form
				:inline="false"
				:model="mainform"
				class="demo-form-inline"
				ref="craftInfoRef"
				label-width="80px"
				key="userListFrom1"
				:rules="rules"
				hide-required-asterisk
			>
				<el-form-item label="用户名称">
					<change-user-input
						ref="changeUserInput"
						@sendValue="(data) => getData(data, 1)"
						@clear="clear(1)"
					></change-user-input>
				</el-form-item>
				<div class="goods_container_header">
					<el-form-item
						label="物品"
						prop="formsp.goods_spu_id"
						:rules="rules.goods_spu_id"
					>
						<change-goods-input
							ref="changeGoodsRef"
							url="2"
							@clear="clear(2)"
							@sendValue="(data) => getData(data, 2)"
						></change-goods-input>
					</el-form-item>
					<el-form-item label="借出数量" prop="formsp.num" :rules="rules.num">
						<el-input
							v-model.trim="mainform.formsp.num"
							ref="focusw2"
							placeholder="数量"
							clearable
							class="wid140"
							@keyup.enter.native="handleAddGoods"
						></el-input>
					</el-form-item>
					<div class="btns">
						<el-button type="primary" v-repeatClick @click="handleAddGoods"
							>确认(回车)</el-button
						>
						<el-button class="reset marginLeft5" type="info" @click="reset"
							>重置</el-button
						>
					</div>
				</div>
				<div class="goods_container_body main_taf main_table">
					<el-table
						ref="multipleTable"
						:data="mainform.list"
						element-loading-text="加载中"
						fit
						border
						highlight-current-row
					>
						<el-table-column label="序号" width="80">
							<template slot-scope="scope">{{ scope.$index + 1 }}</template>
						</el-table-column>
						<el-table-column
							label="物品名称"
							prop="name"
							min-width="100"
							:show-overflow-tooltip="true"
						/>
						<el-table-column
							label="单位"
							prop="unit"
							:show-overflow-tooltip="true"
						>
						</el-table-column>
						<el-table-column
							label="库存剩余量"
							prop="inventory_num"
							:show-overflow-tooltip="true"
							min-width="140"
						>
							<template #header>
								<span>库存剩余量</span>
								<el-tooltip class="item" effect="dark" placement="top">
									<div slot="content">注释：剩余数量=库存数量-借出数量</div>
									<i class="el-icon-question icon"></i>
								</el-tooltip>
							</template>
							<template slot-scope="scope">
								{{ return_inventory_num(scope.row) }}
							</template>
						</el-table-column>

						<el-table-column label="借出数量" min-width="120" prop="price">
							<template #header>
								<span>借出数量</span>
							</template>
							<template slot-scope="scope">
								<el-form-item
									label-width="10px"
									label=" "
									:prop="'list.' + scope.$index + '.num'"
									:rules="rules.num"
								>
									<el-input-number
										v-model.trim="scope.row.num"
										:ref="'price' + scope.row.num"
										:precision="2"
										:controls="false"
										placeholder="单价"
										class="wid100"
									></el-input-number>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column
							label="管理操作"
							prop="name"
							width="160"
							align="center"
							fixed="right"
							:show-overflow-tooltip="true"
						>
							<template slot-scope="scope">
								<el-link @click="handeleDel(scope)">删除</el-link>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<el-form-item label="备注" prop="remark">
					<el-input
						type="textarea"
						style="max-width: 400px"
						:rows="2"
						placeholder="请输入内容"
						v-model="mainform.remark"
					>
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="showDialog_copy = false">取消</el-button>
				<el-button
					type="primary"
					v-repeatClick
					@click="handleComfrim"
					:loading="saveLoading"
					>提交</el-button
				>
			</div></el-dialog
		>
	</div>
</template>
<script>
	import rules from "@/rules/warehouse/turnoverGoods/recordLend.js";
	import {
		turnoverOrder_searchItems,
		turnoverOrder_add,
	} from "@/api/warehouse/warehouseTurnOrder.js";
	import { jsonStringifyBack } from "@/utils";
	export default {
		name: "",
		props: {
			showDialog: {
				type: Boolean,
				default: false,
			},
			id: {
				type: Number | String,
				default: "",
			},
		},

		computed: {
			showDialog_copy: {
				get: function () {
					return this.showDialog;
				},
				set: function (newval) {
					this.$emit("update:showDialog", newval);
				},
			},
		},
		data() {
			return {
				rules: rules,
				mainform: {
					uid: "",
					remark: "",
					type: 1,
					formsp: {
						goods_data: {},
						num: "",
						goods_spu_id: "",
					},
					list: [],
				},
				saveLoading: false,
			};
		},
		methods: {
			//获取用户和商品的数据
			getData(data, type) {
				switch (type) {
					case 1:
						let uid = data.info.user_id;
						this.mainform.uid = uid;

						break;
					case 2:
						this.mainform.formsp.goods_data = data;
						this.mainform.formsp.goods_spu_id = data.goods_spu_id;
						this.$refs["craftInfoRef"].clearValidate(["formsp.goods_spu_id"]);
						this.$nextTick(() => {
							this.$refs["focusw2"].focus();
						});
						break;
				}
			},
			// 清除用户和商品的数据
			clear(type) {
				switch (type) {
					case 1:
						this.mainform.uid = "";
						break;
					case 2:
						break;
				}
			},
			// 确认回车添加商品
			handleAddGoods() {
				let arr = ["formsp.num", "formsp.goods_spu_id"];
				Promise.all(
					arr.map((item) => {
						let p = new Promise((resolve, reject) => {
							this.$refs["craftInfoRef"].validateField(item, (error) => {
								resolve(error);
							});
						});
						return p;
					})
				).then(async (data) => {
					let list = data.filter((item) => {
						if (item !== undefined && item !== "" && item !== null) {
							return item;
						}
					});
					if (list.length == 0) {
						await this.handleData();
						await this.reset();
						this.$nextTick(() => {
							this.$refs["changeGoodsRef"].focus();
							this.$refs["craftInfoRef"].clearValidate([
								"formsp.goods_spu_id",
								"formsp.num",
							]);
						});
					} else {
					}
				});
			},
			// 库存数量
			return_inventory_num(row) {
				let inventory_num = 0;
				inventory_num = parseFloat(row.old_inventory_num) - parseFloat(row.num);
				inventory_num >= 0
					? parseFloat(this.$toFixed(parseFloat(inventory_num)))
					: 0;
				return inventory_num;
			},
			//处理数据
			handleData() {
				let formsp = this.mainform.formsp;
				let inventory_num = formsp.goods_data.goods_spu.inventory.num;
				inventory_num = parseFloat(inventory_num) - parseFloat(formsp.num);
				let obj = {
					item_id: formsp.goods_data.id,
					goods_id: formsp.goods_data.goods_id,
					goods_spu_id: formsp.goods_data.goods_spu_id,
					num: parseFloat(formsp.num),
					price: formsp.goods_data.goods_spu.inventory.price,
					old_inventory_num: formsp.goods_data.goods_spu.inventory.num,
					name: formsp.goods_data.name,
					unit: formsp.goods_data.goods_spu.spu_unit.title,
				};

				let arr = this.mainform.list.filter(
					(e) => e.goods_spu_id == obj.goods_spu_id
				);
				if (arr.length == 0) {
					this.mainform.list.push(obj);
				}
			},
			// 重置
			reset() {
				this.mainform.formsp.goods_data = {};
				this.mainform.formsp.num = "";
				this.mainform.formsp.goods_spu_id = "";
				this.$refs["changeGoodsRef"].name = "";
			},
			// 删除
			handeleDel(scope) {
				let index = scope.$index;
				this.mainform.list.splice(index, 1);
			},
			// 提交
			handleComfrim() {
				if (this.mainform.list.length == 0) {
					this.$message.error("请选择借出物品");
					return;
				}
				if (!this.mainform.uid) {
					this.$message.error("请选择用户");
					return;
				}
				let form = JSON.parse(JSON.stringify(this.mainform, jsonStringifyBack));
				let overInventory = form.list.filter((e) => {
					return parseFloat(e.old_inventory_num) - parseFloat(e.num) < 0;
				});
				if (overInventory.length > 0) {
					this.$confirm(
						`有【${overInventory.length}】超出库存量，是否继续？`,
						"提示",
						{
							confirmButtonText: "确定",
							cancelButtonText: "取消",
							type: "warning",
						}
					)
						.then(() => {
							this.commit(form);
						})
						.catch(() => {});
				} else {
					this.commit(form);
				}
			},
			commit(form) {
				let list = form.list.map((e) => {
					let { old_inventory_num, inventory_num, name, unit, ...sz } = e;
					return { ...sz };
				});
				this.saveLoading = true;
				let data = {
					uid: form.uid,
					remark: form.remark,
					type: form.type,
					list: JSON.stringify(list),
				};
				turnoverOrder_add(data).then((res) => {
					if (res.errcode == 0) {
						this.$message.success("添加成功");
						this.showDialog_copy = false;
						this.$emit("refresh");
					} else {
						this.$message.error(res.errmsg);
					}
					this.saveLoading = false;
				});
			},
			closed() {
				this.reset();
				this.mainform.uid = "";
				this.mainform.remark = "";
				this.mainform.list = [];
				this.type = 1;
				this.$refs["changeUserInput"].name = "";
			},
		},
	};
</script>
<style lang='scss' scoped>
.goods_container_header {
	display: flex;
	align-items: flex-start;
	flex-wrap: wrap;
	.btns {
		padding-left: 10px;
	}
}
.goods_container_body {
	margin-bottom: 15px;
}
.main_table /deep/ .el-table--small td .cell {
	height: auto;
	.el-form-item--mini.el-form-item,
	.el-form-item--small.el-form-item {
		margin-top: 10px;
	}
}
.main_table /deep/ .el-table--small td {
	padding: 0;
}
.icon {
	margin-left: 5px;
	transform: translateY(1px);
}
</style>
